package com.example.tccdemo.config;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @describte:配置数据源+Mybatis+事务管理器
 * @program:distribute-transaction
 * @author:zhengdp
 * @create:2021-09-26 17:36:54
 **/
@Configuration
@MapperScan(value = "com.example.tccdemo.db132.dao",sqlSessionFactoryRef = "factoryBean132")
public class ConfigDb132 {

    @Bean("db132")
    public DataSource db131(){
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setUser("zdp");
        mysqlDataSource.setPassword("Log3.1415926");
        mysqlDataSource.setUrl("jdbc:mysql://192.168.0.133:3306/xa_132");
        return mysqlDataSource;
    }

    @Bean("factoryBean132")
    public SqlSessionFactoryBean factoryBean(@Qualifier("db132")DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resourceResolver.getResources("mybatis/db132/*.xml"));
        return sqlSessionFactoryBean;
    }

    @Bean("tm132")
    public PlatformTransactionManager transactionManager(@Qualifier("db132")DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}
